<template>
  <view class="container">
    <ve-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <ve-card>
        <ve-form-item prop="endTime" required label="续租后还车时间">
          <ve-date-picker
            v-model="form.endTime"
            valueFormat="YYYY-MM-DD 23:59:59"
            mode="date"
            :minDate="dayjs(curItem.startTime).valueOf()"
            @confirm="calcRentDays"
          />
          <template #rightContent>
            <view class="rent-days"> 续租时长：{{ leaseNumberStr || '- 天' }} </view>
          </template>
        </ve-form-item>
        <ve-form-item label="续租备注" :borderBottom="false" labelPosition="top">
          <ve-input type="textarea" v-model="form.remark" :maxlength="200" />
        </ve-form-item>
      </ve-card>
    </ve-form>

    <footer-box id="footer-box">
      <ve-button size="long" type="primary" :loading="okLoading" @click="onClick">确定</ve-button>
    </footer-box>
  </view>

  <!-- 二次确认 -->
  <ve-confirm titleText="请确认是否排车？" v-model="confirmVisible" @confirm="confirmSubmit">
    <view v-for="(it, i) in resultMsg" :key="i">{{ it }}</view>
  </ve-confirm>
</template>

<script setup lang="ts">
  import footerBox from '../form/components/footerBox.vue'

  import { ref } from 'vue'
  import dayjs from 'dayjs'
  import { onLoad } from '@dcloudio/uni-app'
  import { computeRentDayAPI, getOrdrDetailsAPI, platoonCarCheckAPI, modifyReletAPI } from '@/api/order/lOrder'

  const okLoading = ref(false)
  const formRef = ref()
  const form = ref({
    endTime: '',
    remark: '',
    leaseNumberStr: '',
  })

  // 处理默认值
  // 租赁周期限制最小天数 1 天
  const timeRangeValidator = (rule: any, value: string, callback: (msg?: string) => void) => {
    if (value) {
      let start = curItem.value.startTime
      let end = value
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        if (diff !== 0 && diff < 23 * 59 * 59 * 1000) {
          callback('续租时长最短为1天')
        }
      }
    }
    callback()
  }

  const rules = {
    endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
  }
  const orderInfo = ref<any>({})

  // 计算租期
  const leaseNumberStr = ref()
  const leaseMonthsNumber = ref()
  const calcRentDays = () => {
    let startTime = dayjs(curItem.value.startTime).format('YYYY-MM-DD 00:00:00')
    let value = form.value.endTime
    if (value) {
      // 计算租期
      const param = {
        expectedUseCarTime: startTime,
        expectedReturnCarTime: value,
      }
      computeRentDayAPI(param).then((res) => {
        let result = res.result
        let dateStr = result.dateStr
        leaseNumberStr.value = dateStr
        leaseMonthsNumber.value = result.months
        form.value.leaseNumberStr = dateStr
      })
    } else {
      leaseNumberStr.value = undefined
      form.value.leaseNumberStr = ''
    }
  }

  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback: () => void) => {
    const params = {
      refId: orderInfo.value.id,
      startTime: dayjs(curItem.value.startTime).format('YYYY-MM-DD 00:00:00'),
      endTime: form.value.endTime,
      useType: 3,
      carId: orderInfo.value.carId,
    }
    platoonCarCheckAPI(params).then((res) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }

  const reletFn = () => {
    modifyReletAPI({
      id: curItem.value.id,
      endTime: form.value.endTime,
      remark: form.value.remark,
    })
      .then(() => {
        uni.showToast({ title: '修改续租成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateBack()
        }, 300)
      })
      .finally(() => {
        okLoading.value = false
      })
  }

  // 二次询问确认
  const confirmSubmit = () => {
    reletFn()
  }

  /** 获取订单详情 */
  const getOrderDetails = (option: any) => {
    console.log('getOrderDetails', option)

    getOrdrDetailsAPI({ id: option.orderId }).then((res: any) => {
      const result = res.result
      orderInfo.value = result.orderInfo

      if (curItem.value.endTime) {
        form.value.endTime = dayjs(curItem.value.endTime).format('YYYY-MM-DD 23:59:59')
      }

      calcRentDays()
    })
  }

  const onClick = () => {
    formRef.value.validate((valid: any) => {
      if (valid) {
        okLoading.value = true
        platoonCarVerify(() => {
          reletFn()
        })
      }
    })
  }

  const curItem = ref<any>({})
  onLoad((option: any) => {
    curItem.value = JSON.parse(option.curItem)

    form.value.remark = curItem.value.remark
    console.log('option', option, curItem.value)
    getOrderDetails(option)
  })
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    padding: 12px 12px;
    background: #f7f8fa;

    .rent-days {
      font-size: 30rpx;
      text-align: right;
      color: #3072f6;
    }
  }

  #footer-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 999;
  }
</style>
